import { app_version, APPSTORE_APPID } from '@/common/config/config.js'
import { checkUpdateVersion } from '@/common/api/api.js'

// 比较版本号大小
function compareVersion(version1, version2) {
	const regex = /(\d+)/g
	const v1 = version1.match(regex).map(Number)
	const v2 = version2.match(regex).map(Number)
	return v1 > v2
}
//下载更新包
const downLoad = (url)=>{
	if (!url) {
		uni.showToast({icon: 'none',title: '无效的下载地址'})
		return false
	}
	// 下载文件
	uni.showLoading({title: '更新中'})
	uni.downloadFile({
		url: url,
		success(res) {
			uni.hideLoading()
			console.log('下载结果：',res)
			if (res.statusCode === 200) {
				uni.showToast({title: '下载成功'})
				plus.runtime.install(res.tempFilePath)
			}
			else{
				uni.showToast({title: '安装失败'})
			}
		},
		fail(err) {
			uni.hideLoading()
		}
	})
}
//获取app版本号
export const getAppVersion = ()=>{
	plus.runtime.getProperty(plus.runtime.appid,(info)=>{
		console.log(info)
	})
}
// 检测新版本
export const updateVersion = async () => {
	const platform = uni.getSystemInfoSync().platform
	let params = {}
	params.appName = '汇拓宝'
	if (platform == 'ios') {
		params.client = 'ios'
	} else {
		params.client = 'android'
	}
	const res = await checkUpdateVersion(params)
	const data = res.result
	console.log('++++++++版本信息：', res)
	if (data) {
		const newVersion = data.versionCode
		const oldVersion = app_version()
		if (compareVersion(newVersion, oldVersion)) {
			// 有新版本，提示更新
			console.log('有新版本，提示更新')
			uni.showModal({
				title: '版本更新',
				content: data.updateHint,
				showCancel: data.updateType == '01',
				confirmText: '立即更新',
				success(res) {
					console.log(res)
					if (res.confirm) {
						if (platform == 'ios') {
							plus.runtime.launchApplication({
								action: `itms-apps://itunes.apple.com/cn/app/id${APPSTORE_APPID}?mt=8`
							}, function(e) {
								uni.showToast({ title: '跳转失败，请手动前往 App Store更新', icon: 'none' })
							})
						} else {
							downLoad(data.path)
						}
					}

				}
			})
		}
	}

}
